package com.vehicle_demo.service;

import com.vehicle_demo.dao.VehicleInfoDao;
import com.vehicle_demo.dao.WarnRecordDao;
import com.vehicle_demo.dao.WarningRuleDao;
import com.vehicle_demo.dto.Response;
import com.vehicle_demo.dto.Signal;
import com.vehicle_demo.entity.WarningRecord;
import com.vehicle_demo.entity.WarningRule;
import com.vehicle_demo.utils.WarnUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class WarningService {

    @Autowired
    private VehicleInfoDao vehicleInfoDao;

    @Autowired
    private WarningRuleDao warningRuleDao;
    @Autowired
    private WarnRecordDao warnRecordDao;


    /**
     * 根据输入的信号数据进行预警分析并返回结果
     * @param signals 包含信号数据的列表
     * @return 包含预警信息的List<Response>结果
     */
    public List<Response> analyzeWarnings(List<Signal> signals) {
        List<Response> resultList = new ArrayList<>();;

        for (Signal signal : signals) {
            int carId = signal.getCarId();
            int warnId = signal.getWarnId();
            Map<String, Object> signalData = signal.getSignal();

            // 查询车辆信息，获取电池类型等
            String batteryType = vehicleInfoDao.findBatteryTypeByCarId(carId);

            // 根据 warnId 或
            List<WarningRule> rules;
            if (warnId != 0) {
                rules = warningRuleDao.findBatteryTypeByCarId(batteryType, warnId);
            } else {
                rules = warningRuleDao.findByBatteryType(batteryType);
            }

            // 根据规则计算预警等级,没有给规则编号就遍历电压和电流规则
            for (WarningRule rule : rules) {
                String warningRule = rule.getWarn_rule();
                int warnLevel = WarnUtils.calculateWarnLevel(signalData, warningRule);
                //将匹配预警规则生成utils里面的工具类，里面的方法写成静态的

                // 构造返回的数据结构
                Response response = new Response();
                response.setCarId(carId);
                response.setBatteryType(batteryType);
                response.setWarnName(rule.getWarnName());
                response.setWarnLevel(warnLevel);
                resultList.add(response);



                //响应数据入数据库
                WarningRecord warningRecord = new WarningRecord();
                warningRecord.setCarId(carId);
                warningRecord.setBatteryType(batteryType);
                warningRecord.setWarnName(rule.getWarnName());
                warningRecord.setWarnLevel(warnLevel);
                warnRecordDao.insert(warningRecord);
            }
        }

        return resultList;
    }

}






